import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import Tab from './../components/common/TabVertical'
import Content from './../components/common/Content'
import Page from './../components/common/Page'
import About from './../components/Org/About'
import Company from './../components/Org/Company'
import ask from '../serve/api';
import qs from 'query-string'
import styles from './Org.module.scss'

export default withRouter(class Org extends Component {
  constructor(props) {
    super(props)
    const { type } = qs.parse(props.location.search)
    let selected = 0
    if (type === 'about') {
      selected = 1
    } else if (type === 'activity') {
      selected = 2
    }
    this.state = {
      tabs: [{
        name: '成员单位',
        list : [],
      }, {
        name: '关于联盟'
      }, {
        name: '活动动态'
      }],
      selected,
      allianceInfo: '',
      activity: []
    }
  }

  onTab(item, index) {
    this.setState({
      selected: index
    });
    if(index === 0){
      this.fetchMemberList();
    };
  }

  getCurrentPage() {

  }

  componentDidMount() {
    this.getAllianceInfo()
    this.getAvtivity()
    this.fetchMemberList()
  }

  async getAllianceInfo() {
    const { code, result } = await ask.listAlliance()
    if (code !== '000000') {
      return
    }
    this.setState({
      allianceInfo: result.about
    })
  }

  async getAvtivity() {
    const { code, result } = await ask.listOrgApi({ page: 1, pageSize: 10 })
    if (code !== '000000') return
    if (result) {
      this.setState({
        activity: result
      })
    }
  }

  async fetchMemberList (){
    const {code, result} = await ask.listAllianceMember();
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };
      const {tabs} = this.state;
      tabs[0].list = result || [];
      this.setState({
        tabs
      });
    } catch (error) {
      console.log(error);
    }
  }

  onCompany({item}) {
    const { history } = this.props;
    const url = `/org/main?orgId=${item.id}`;
    history.push(url);
  }

  onItem(item) {
    this.props.history.push(`/mainPage/commonDetail/org/${item.id}`)
  }

  render() {
    const { selected, tabs, allianceInfo, activity } = this.state
    return (
      <div className={styles.org_container}>
        <Tab tabs={this.state.tabs} selected={selected} onTab={(item, index) => this.onTab(item, index)} />
        <div className={styles.org_content}>
          {selected === 0 && <Company onTab={index => this.onCompany(index)} list={tabs[selected].list}/>}
          {selected === 1 && <About content={allianceInfo || ''} />}
          {selected === 2 && <div className={styles.activity_div}>
            <Content datas={activity} onItem={item => this.onItem(item)} />
            <Page
              pageConfig={{totalPage: 10}}
              pageCallbackFn={() => this.getCurrentPage()}
            />
          </div>}
        </div>
      </div>
    )
  }
})
